<?php

namespace app\partner\controller;

use app\common\controller\CommonService;
use think\console\Command;
use think\Controller;
use think\Db;
use think\facade\Validate;
use think\Request;

class Earnings extends Controller
{

    /**
     *
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function accountInfo()
    {
        $partnerId = \request()->partnerId;
        $partner = Db::name('partner')->field('money,freeze_money')->find($partnerId); //余额与冻结资金
        $data['totalMoney'] = Db::name('partner_liushui')->where('partner_id', $partnerId)->where('money', '>', 0)->sum('money'); //总金额
        $data = array_merge($partner, $data);
        $data['nowMonthEstimate'] = $this->getData(strtotime(date('Y-m-01')), strtotime(date('Y-m-t'))); //本月预估
        $data['nowMonthEstimate'] = round($data['nowMonthEstimate'],3);
        $data['lastMonthEstimate'] = $this->getData(strtotime(date('Y-m-1', strtotime('last month'))), strtotime(date('Y-m-01'))); //上月预估
        $data['lastMonthEstimate'] = round($data['lastMonthEstimate'],3);
        $data['lastMonthMoney'] = Db::name('partner_liushui')->whereBetween('time',[strtotime(date('Y-m-1', strtotime('last month'))), strtotime(date('Y-m-01'))])->where('partner_id', $partnerId)->where('lb', 'in', [1, 2, 3, -1, -2, -3])->sum('money');//上月结算金额
        $data['lastMonthMoney'] = round($data['lastMonthMoney'],3);
        return CommonService::success($data);
    }

    /**
     * 收支明细
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function accountList()
    {
        $partnerId = \request()->partnerId;
        $data = Db::name('partner_liushui')
            ->field('time,lb,money,yue')
            ->where('partner_id', $partnerId)
            ->where('lb', 'not in', [1, 2, 3, -1, 2, -3])
            ->unionAll(function ($query) use ($partnerId) {
                $query->name('partner_liushui')->where('partner_id', $partnerId)->where('lb', 'in', [1, 2, 3, -1, 2, -3])->field("DATE_FORMAT(FROM_UNIXTIME(time),'%Y-%m-25') as time,lb,sum(money) as money,max(yue) as yue")->group("DATE_FORMAT(FROM_UNIXTIME(time),'%Y-%m-25')")->select();
            })->page(input('page', 1), input('listRows', 10))->order('time', 'desc')->select();
        foreach ($data as $k => $v) {
            if (is_numeric($v['time'])) {
                $data[$k]['time'] = date('Y-m-d H:i:s', $v['time']);
            }
            switch ($v['lb']) {
                case in_array($v['lb'], [1, 2, 3, -1, -2, -3]):
                    $data[$k]['lb'] = '收益结算';
                    break;
                case 4:
                    $data[$k]['lb'] = '提现';
                    break;
                default:
                    $data[$k]['lb'] = '其他';
                    break;
            }
        }
        return CommonService::success($data);
    }


    /**
     * 提现记录
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function withdrawList()
    {
        $partnerId = \request()->partnerId;
        $db = Db::name('partner_check_log')
            ->field('add_time,check_value,check_before_value,check_status,check_time,cause')
            ->where('partner_type', 2)
            ->where('partner_id', $partnerId)
            ->where('check_type', 3);
        if (input('startTime') && input('endTime')) {
            $db = $db->whereBetween('add_time', [strtotime(input('startTime')), strtotime(input('endTime'))]);
        }
        if (input('status')) {
            $db = $db->where('check_status', input('status'));
        }
        $total = $db->count();
        $list = $db->page(input('page', 1), input('listRows'))->order('id', 'desc')->select();
        foreach ($list as $k => $v) {
            $list[$k]['add_time'] = date('Y-m-d H:i:s', $v['add_time']);
            $list[$k]['check_time'] = date('Y-m-d H:i:s', $v['check_time']);
            switch ($v['check_status']) {
                case 0;
                    $list[$k]['check_status'] = '提现失败';
                    break;
                case 1;
                    $list[$k]['check_status'] = '提现成功';
                    break;
                case 2;
                    $list[$k]['check_status'] = '提现失败';
                    break;
            }
        }
        $data['list'] = $list;
        $data['total'] = $total;
        return CommonService::success($data);
    }

    /**
     * 申请提现时的信息
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getWithdrawInfo(Request $request)
    {
        $partnerId = \request()->partnerId;
        $WithdrawInfo= Db::name('user_manage')
            ->alias('u')
            ->join('partner s', 's.uid=u.id', 'LEFT')
            ->where('s.id', $partnerId)
            ->field('u.payee_name,u.alipay_id,u.tel,s.money,s.withdraw_password,s.freeze_money')
            ->find();
        if (!empty($WithdrawInfo['payee_name']) && !empty($WithdrawInfo['alipay_id'])){
            $WithdrawInfo['alipay_type'] = 1;
        } else {
            $WithdrawInfo['alipay_type'] = 0;
        }
        if ($WithdrawInfo['freeze_money'] > 0){
            $WithdrawInfo['Withdraw_type'] = 1;
            $WithdrawInfo['Withdraw_money'] = $WithdrawInfo['freeze_money'];
        } else {
            $WithdrawInfo['Withdraw_type'] = 0;
            $WithdrawInfo['Withdraw_money'] = 0;
        }
        return CommonService::success($WithdrawInfo);
    }

    /**
     * 提现申请
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function WithdrawApply(Request $request)
    {
        $partnerId = $request->partnerId;
        $requestData = $request->post();
        $validate = Validate::make([
            'payee_name|姓名' => 'require',
            'alipay_id|支付宝号' => 'require',
            'withdraw_money|提现金额' => 'require',
            'withdraw_pass|提现密码' => 'require',
        ]);
        if (!$validate->check($requestData)){
            return CommonService::error($validate->getError());
        }
        $uid = Db::name('user_manage')
            ->where('payee_name',$requestData['payee_name'])
            ->where('alipay_id',$requestData['alipay_id'])
            ->value('id');
        $partnerInfo = Db::name('partner')
            ->where('uid',$uid)
            ->field('id,withdraw_password,money,freeze_money')
            ->find();
        if ($partnerId != $partnerInfo['id']){
            return CommonService::error(1);
        }
        if ($requestData['withdraw_money'] <= 0 || $requestData['withdraw_money'] > $partnerInfo['money']){
            return CommonService::error('请输入正确的提现金额！');
        }
        if ($requestData['withdraw_pass'] != $partnerInfo['withdraw_password']){
            return CommonService::error('请输入正确的提现密码！');
        }
        if ($partnerInfo['freeze_money'] > 0){
            return CommonService::error('您有正在审核的提现！');
        }
        Db::startTrans();
        try {
            Db::name('partner')->where('id', $partnerId)->update([
                'freeze_money' => $requestData['withdraw_money'],
            ]);
            Db::name('partner_check_log')->insert([
                'partner_id' => $partnerInfo['id'],
                'check_type' => 3,
                'check_before_value' => $requestData['withdraw_money'],
                'partner_type' => 2,
                'check_status' => 0,
                'add_time' => time(),
            ] );
            Db::commit();
            return CommonService::success([],'提现申请中！');
        } catch (\Exception $e) {
            Db::rollback();
            return CommonService::error(0);
        }

    }

    /**
     * 收益结算记录
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getProfitInfo(Request $request)
    {
        $partnerId = $request->partnerId;
        $year = !empty(input('year')) ? input('year') : date('Y');
        for ($i = 1; $i <= 12; $i++) {
            $startTime = $year.'-'.$i.'-01 00:00:00';
            $endTime = date('Y-m-d H:i:s', strtotime($startTime.'+' . 1 . 'month'));
            $data[$i] = $this->getSetData(strtotime($startTime), strtotime($endTime), $partnerId);
        }
        return CommonService::success($data);
    }
    /**
     * 详细记录
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getMoneyProfitList(Request $request)
    {
        $partnerId = $request->partnerId;
        $year = !empty(input('year')) ? input('year') : date('Y');
        for ($i = 1; $i <= 12; $i++) {
            $startTime = $year.'-'.$i.'-01 00:00:00';
            $endTime = date('Y-m-d H:i:s', strtotime($startTime.'+' . 1 . 'month'));
            $data[$i]['profit'] = $this->getSetData(strtotime($startTime), strtotime($endTime), $partnerId);
            $data[$i]['buy'] = $this->getBuyData(strtotime($startTime), strtotime($endTime), $partnerId);
        }
        foreach ($data as $k => $v){
            $profit = $v['profit'];
            $buy = $v['buy'];
            $date[$k]['zhouqi'] = $year.'年'.$k.'月';
            $date[$k]['tb_profit'] = $profit['tb'];
            $date[$k]['jd_profit'] = $profit['jd'];
            $date[$k]['pdd_profit'] = $profit['pdd'];
            $date[$k]['lei_profit'] = $profit['tb'] + $profit['jd'] + $profit['pdd'];
            if ($profit['tb'] == 0 && $profit['jd'] == 0 && $profit['pdd'] == 0){
                $date[$k]['tb_buy'] = 0;
                $date[$k]['jd_buy'] = 0;
                $date[$k]['pdd_buy'] = 0;
                $date[$k]['lei_buy'] = 0;
            } else {
                $date[$k]['tb_buy'] = $buy['tb'];
                $date[$k]['jd_buy'] = $buy['jd'];
                $date[$k]['pdd_buy'] = $buy['pdd'];
                $date[$k]['lei_buy'] = $buy['tb'] + $buy['jd'] + $buy['pdd'];
                $date[$k]['lei_buy'] = round($date[$k]['lei_buy'],3);
            }
        }
        $yearTime = time();
        foreach ($date as $k => $v){
            $zhouQi = date_parse_from_format('Y年m月',$date[$k]['zhouqi']);
            $zhou = mktime(0,0,0,$zhouQi['month'],0,$zhouQi['year']);
            if ($zhou <= $yearTime){
                $datc[$k]['zhouqi'] = $v['zhouqi'];
                $datc[$k]['tb_profit'] = $v['tb_profit'];
                $datc[$k]['jd_profit'] = $v['jd_profit'];
                $datc[$k]['pdd_profit'] = $v['pdd_profit'];
                $datc[$k]['lei_profit'] = round($v['lei_profit'],3);
                $datc[$k]['tb_buy'] = $v['tb_buy'];
                $datc[$k]['jd_buy'] = $v['jd_buy'];
                $datc[$k]['pdd_buy'] = $v['pdd_buy'];
                $datc[$k]['lei_buy'] = round($v['lei_buy'],3);
            }
        }
        if (!empty($datc)){
            $datc = array_reverse($datc);
        } else {
            $datc = [];
        }
        return CommonService::success($datc);
    }
    /**
     * 根据时间查询订单收益
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function getData($startTime, $endTime, $partnerId = null)
    {
        if (!$partnerId) $partnerId = \request()->partnerId;
        $tbOrder = Db::name('tb_order')
            ->leftJoin('user_manage u','tb_order.uid = u.id')
            ->where('u.partner_id', $partnerId)
            ->where('order_type', 1)
            ->where('order_status', '<>', 0)
            ->where('is_weiquan', 0)
            ->whereBetween('order_time', [date('Y-m-d H:i:s', $startTime), date('Y-m-d H:i:s', $endTime)])
            ->sum('partner_rebate_fee');
        $jdOrder = Db::name('jd_order')
            ->leftJoin('user_manage u','jd_order.uid = u.id')
            ->where('u.partner_id', $partnerId)
            ->where('order_status', '<>', 0)
            ->whereBetween('order_time', [$startTime * 1000, $endTime * 1000])
            ->sum('partner_rebate_fee');
        $pddOrder = Db::name('pdd_order')
            ->leftJoin('user_manage u','pdd_order.uid = u.id')
            ->where('u.partner_id', $partnerId)
            ->where('order_status', '<>', 0)
            ->whereBetween('order_time', [$startTime, $endTime])
            ->sum('partner_rebate_fee');

        return $tbOrder + $jdOrder + $pddOrder;
    }
    /**
     * 根据时间查询收益结算
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getSetData($startTime, $endTime, $partnerId = null)
    {
        if (!$partnerId) $superPartnerId = \request()->partnerId;
        $data['tb'] = db('partner_liushui')
            ->where('partner_id',$partnerId)
            ->whereBetween('time',[$startTime,$endTime])
            ->where('lb', 'in', [1,-1])
            ->where('order_type',1)
            ->sum('money');
        $data['jd'] = db('partner_liushui')
            ->where('partner_id',$partnerId)
            ->whereBetween('time',[$startTime,$endTime])
            ->where('lb', 'in', [2,-2])
            ->where('order_type',2)
            ->sum('money');
        $data['pdd'] = db('partner_liushui')
            ->where('partner_id',$partnerId)
            ->whereBetween('time',[$startTime,$endTime])
            ->where('lb', 'in', [3,-3])
            ->where('order_type',3)
            ->sum('money');
        return $data;
    }
    /**
     * 根据时间查询订单销售额
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function getBuyData($startTime, $endTime, $partnerId = null)
    {
        if (!$partnerId) $partnerId = \request()->partnerId;
        $tbOrder = Db::name('tb_order')
            ->leftJoin('user_manage u','tb_order.uid = u.id')
            ->where('u.partner_id',$partnerId)
            ->where('order_type', 1)
            ->where('order_status', '<>', 0)
            ->where('is_weiquan', 0)
            ->whereBetween('order_time', [date('Y-m-d H:i:s', $startTime), date('Y-m-d H:i:s', $endTime)])
            ->sum('user_buy_price');
        $jdOrder = Db::name('jd_order')
            ->leftJoin('user_manage u','jd_order.uid = u.id')
            ->where('u.partner_id',$partnerId)
            ->where('order_status', '<>', 0)
            ->whereBetween('order_time', [$startTime * 1000, $endTime * 1000])
            ->sum('user_buy_price');
        $pddOrder = Db::name('pdd_order')
            ->leftJoin('user_manage u','pdd_order.uid = u.id')
            ->where('u.partner_id',$partnerId)
            ->where('order_status', '<>', 0)
            ->whereBetween('order_time', [$startTime, $endTime])
            ->sum('user_buy_price');
        $data['tb'] = $tbOrder;
        $data['jd'] = $jdOrder;
        $data['pdd'] = $pddOrder;
        return $data;
    }

}
